<?php
class Cerad_Session
{
	protected $context   = NULL;
	protected $sessionId = NULL;
	
	function __construct($context)
	{
		$this->context = $context;
		
		$this->sessionId = $context->getRequest()->getCookie('zayso2009');
	}
	function isTransient()
	{
		if ($this->sessionId) return FALSE;
		
		return TRUE;
	}
	/* --------------------
	 * Need some sort of session id clear which should reset the cookie as well
	 */
	function getData($name)
	{
		if (!$this->sessionId) return NULL; // new Cerad_Data();
		
		$params = array(
		    'session_id' => $this->sessionId,
		    'name'       => $name
		);
		$sql = <<<EOT
SELECT
  data AS data
FROM  session_data
WHERE session_id = :session_id AND name = :name
EOT;
        $rows = $this->context->getDb()->fetchRows($sql,$params);
        
        if (count($rows) < 1) return NULL; // new Cerad_Data();
        
        $data = unserialize($rows[0]['data']);
        
        return $data;
	}
	function setData($name,$data)
	{
		// $this->sessionId = NULL;
		if ($this->sessionId) $sessionId = $this->sessionId;
		else {
			$this->sessionId = $sessionId = md5(uniqid(rand(), true));
			
			// setcookie('zayso2009',$sessionId,mktime(0, 0, 0, 12, 31, 2015));
			$expires = date(DATE_RFC822,mktime(0, 0, 0, 12, 31, 2020));
			
			$response = $this->context->getResponse();
			$response->setHeader(
				'Set-cookie',
				"zayso2009={$sessionId}; expires={$expires}"
//				"zayso2009={$sessionId}; expires=Thu, 31-Dec-2015 06:00:00 GMT"
			);
		}
		// die($sessionId);
		$db = $this->context->getDb();
				
		$params = array(
		    'session_id' => $sessionId,
		    'name'       => $name
		);

		$sql = <<<EOT
DELETE FROM session_data
WHERE session_id = :session_id AND name = :name
EOT;
		$db->execute($sql,$params); // die($cnt);
		
		$params['data'] = serialize($data);
		
		$sql = <<<EOT
INSERT INTO session_data (session_id,name,data)
VALUES(:session_id,:name,:data)
EOT;
		$db->execute($sql,$params);
		
	}
}
?>